package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.domain.db.Question;
import com.tanhua.domain.db.Settings;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.SettingsVo;
import com.tanhua.dubbo.api.BlackListApi;
import com.tanhua.dubbo.api.QuestionApi;
import com.tanhua.dubbo.api.SettingsApi;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;

@Service
@Slf4j
public class SettingsService {
    @Reference
    private SettingsApi settingsApi;
    @Reference
    private QuestionApi questionApi;
    @Reference
    private BlackListApi blackListApi;
    @Reference
    private UserApi userApi;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //定义Redis中存储的验证码的key前缀
    private final String SMS_KEY = "SMS_KEY_";
    
    /**
     * 接口名称：用户通用设置 - 读取
     * 需求分析：根据用户id查询通用设置
     */
    public ResponseEntity<Object> querySettings() {
        // 获取登陆用户id
        User user = UserHolder.get();
        
        // 根据用户id查询通用设置表 SELECT * FROM tb_settings WHERE user_id=1
        Settings settings = settingsApi.findByUserId(user.getId());
        if (settings == null) {
            settings = new Settings(); // 容错处理：如果用户没有进行过通用设置，这里会为null
        }
        
        // 根据用户id查询陌生人问题 SELECT * FROM tb_question WHERE user_id=1
        Question question = questionApi.findByUserId(user.getId());
        
        // 通过vo封装接口返回的数据
        SettingsVo vo = new SettingsVo();
        // 对象拷贝：把从tb_settings表查询的登陆用户的通用设置封装到返回结果中
        BeanUtils.copyProperties(settings, vo);
        // 设置陌生人问题
        vo.setStrangerQuestion(question != null ? question.getTxt() : "你喜欢什么？");
        // 设置手机号
        vo.setPhone(user.getMobile());
        
        return ResponseEntity.ok(vo);
    }
    
    /**
     * 接口名称：通知设置 - 保存
     * 需求：添加或者修改通用设置  tb_settings
     */
    public ResponseEntity<Object> saveNotification(Settings param) {
        //1. 获取用户id
        Long userId = UserHolder.getUserId();
        //2. 根据登陆用户id，查询通用设置表
        Settings settings = settingsApi.findByUserId(userId);
        //3. 判断
        if (settings == null) {
            settings = new Settings();
            BeanUtils.copyProperties(param, settings);
            settings.setUserId(userId);
            // 没有查询到，说明用户没有通知设置，执行添加
            settingsApi.save(settings);
        } else {
            // 修改通用设置
            settings.setPinglunNotification(param.getPinglunNotification());
            settings.setLikeNotification(param.getLikeNotification());
            settings.setGonggaoNotification(param.getGonggaoNotification());
            settingsApi.update(settings);
        }
        
        return ResponseEntity.ok(null);
    }
    
    /**
     * 接口名称：设置陌生人问题 - 保存
     * 需求描述：添加或者修改陌生人问题
     */
    public ResponseEntity<Object> saveQuestion(String content) {
        //1. 获取用户id
        Long userId = UserHolder.getUserId();
        //2. 根据登陆用户id，查询通用设置表
        Question question = questionApi.findByUserId(userId);
        //3. 判断
        if (question == null) {
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            // 添加
            questionApi.save(question);
        } else {
            // 修改
            question.setTxt(content);
            questionApi.update(question);
        }
        
        return ResponseEntity.ok(null);
    }
    
    /**
     * 接口名称：黑名单 - 翻页列表
     * 接口路径：GET/users/blacklist
     */
    public ResponseEntity<Object> queryBlacklist(Integer page, Integer pagesize) {
        //1. 获取用户id
        Long userId = UserHolder.getUserId();
        //2. 根据用户id，远程访问Api，查询黑名单用户 (查询的是用户)
        IPage<UserInfo> iPage = blackListApi.findBlacklist(userId, page, pagesize);
        //3. 返回分页对象
        PageResult pageResult =
                new PageResult(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
        return ResponseEntity.ok(pageResult);
    }
    
    /**
     * 接口名称：黑名单 - 移除
     * 接口路径：DELETE/users/blacklist/50
     */
    public ResponseEntity<Object> deleteBlackUser(Long blackUserId) {
        // 获取登陆用户id
        Long userId = UserHolder.getUserId();
        // 移除黑名单
        blackListApi.deleteBlackUser(userId, blackUserId);
        return ResponseEntity.ok(null);
    }
    
    /**
     * 修改手机号：1、发送验证码
     *
     * @return
     */
    public ResponseEntity<Object> sendVerificationCode() {
        String phone = UserHolder.get().getMobile();
        return userService.login(phone);
    }
    
    /**
     * 修改手机号：2、检验验证码
     *
     * @return
     */
    public ResponseEntity<Object> checkVerificationCode(String code) {
        String phone = UserHolder.get().getMobile();
        String redisCode = redisTemplate.opsForValue().get(SMS_KEY + phone);
        HashMap<String, Object> resultMap = new HashMap<>();
        
        Boolean verification = true;//定义一个比较结果的状态，最终可能为true或false
        if (redisCode == null || !redisCode.equals(code)) {
            verification = false;//更改为校验失败状态
        } else {
            //校验成功，从redis里删除验证码
            redisTemplate.delete(SMS_KEY + phone);
        }
        //把校验结果状态放到map里
        resultMap.put("verification", verification);
        return ResponseEntity.ok(resultMap);
    }
    
    /**
     * 修改手机号：3、保存
     *
     * @return
     */
    public ResponseEntity<Object> saveNewPhone(String newPhone, String token) {
        User oldUser = userApi.findByMobile(newPhone);
        if (oldUser == null) {
            User user = UserHolder.get();
            user.setMobile(newPhone);
            userApi.updatePhone(user);
            log.info("=====修改手机号：修改成功");
            //删除Redis缓存
            redisTemplate.delete("TOKEN_KEY_" + token);
            return ResponseEntity.ok(null);
        }
        return ResponseEntity.status(500).body("该手机号已经注册，请更换威注册的手机号重试！");
        
        
    }
    
    
}
